package com.edu.controller;

import com.edu.beans.Admin;
import com.edu.service.AdminsService;
import com.edu.service.impl.AdminsServiceImpl;
import com.edu.utils.CookiesUtils;
import com.edu.utils.DatetimeUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/AdminsServlet.do")
public class AdminsServlet extends HttpServlet {

    AdminsService adminsService = new AdminsServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应编码为 UTF-8
        resp.setContentType("text/html;charset=UTF-8");
        // 获取请求参数中的 action 字段
        String action = req.getParameter("action");
        switch (action) {
            case "adminLogin":
                adminLogin(req, resp);
                break;
            case "adminLogout":
                adminLogout(req, resp);
                break;
            default:
                // 如果 action 不匹配，返回错误信息
                resp.getWriter().write("<script>alert('未知操作');window.location.href='/views/index.jsp';</script>");
                break;
        }
    }

    /**
     * 管理员注销方法
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @throws IOException 如果发生输入输出异常
     */
    private void adminLogout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        session.invalidate();
        resp.sendRedirect("/login.jsp");
    }

    /**
     * 管理员登录处理方法
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @throws IOException 如果发生输入输出异常
     */
    private void adminLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String userCode = req.getParameter("userCode");
            System.out.println("用户名: " + username);
            System.out.println("密码: " + password);
            System.out.println("验证码: " + userCode);
            HttpSession session = req.getSession();
            String systemCode = (String) session.getAttribute("systemCode");
            Admin admin = adminsService.login(username, password);
            if (systemCode.equalsIgnoreCase(userCode)) {
                // 调用服务层进行登录验证
                if (admin != null) {
                    //登录成功，存储用户信息
                    session.setAttribute("nowUser", admin.getUsername());
                    String time = CookiesUtils.getCookie(req, "message");
                    if ("".equals(time)) {
                        //浏览器中没有Cookie
                        time = "欢迎您的登录！";
                        String mytime = DatetimeUtils.now();

                        //创建一个Cookie对象
                        Cookie cookie = new Cookie("message", URLEncoder.encode(mytime, "UTF-8"));
                        //设置有效期
                        cookie.setMaxAge(60 * 60); //有效期60
                        //Cookie写入浏览器
                        resp.addCookie(cookie);
                    } else {
                        //更新一下信的时间
                        time = "上次的登录时间是：" + time;
                        String newTime = DatetimeUtils.now();
                        Cookie cookie = new Cookie("message", URLEncoder.encode(newTime, "UTF-8"));
                        cookie.setMaxAge(60 * 60);
                        resp.addCookie(cookie);
                    }

                    // 将管理员信息存入会话
                    session.setAttribute("admin", admin);
                    session.setAttribute("time", time);
                    resp.sendRedirect("/views/index.jsp");

                } else {
                    // 登录失败
                    req.setAttribute("errorMsg", "账号或密码错误！");
                    req.getRequestDispatcher("/login.jsp").forward(req, resp);
                }
            } else {
                // 验证码错误
                req.setAttribute("errorMsg", "验证码错误！");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);

            }
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }
}
